package com.gaoqi.springboot_shiro.controller;

import com.gaoqi.springboot_shiro.pojo.User;
import com.gaoqi.springboot_shiro.service.UserService;
import com.gaoqi.springboot_shiro.utils.JWTUtils;
import com.sun.deploy.util.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 用于用户登录
     *
     * @return
     */
    @RequestMapping("/login")
    @CrossOrigin
    public String login(User user) {
        //获取实体对象subject
        Subject subject = SecurityUtils.getSubject();
        System.out.println(user);

        try {

            //判断用户权限
            boolean admin = subject.hasRole("sadmin");
            System.out.println(admin);
            //实体对象调用login 进行验证
            subject.login(new UsernamePasswordToken(user.getUname(), user.getPswd()));

            //如果验证通过
            if (subject.isAuthenticated()) {
                return "redirect:/index.html";
            } else {
                return "redirect:/error.html";
            }

        } catch (UnknownAccountException e) {
            e.printStackTrace();
            return "redirect:/error.html";
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            return "redirect:/error.html";
        }
    }

    @RequestMapping(value = "/log", method = RequestMethod.POST)
    @CrossOrigin
    public String log(@RequestBody User user) {

        //获取实体对象subject
        Subject subject = SecurityUtils.getSubject();

        try {
            //实体对象调用login 进行验证
            subject.login(new UsernamePasswordToken(user.getUname(), user.getPswd()));

            //判断用户权限 和角色（授权认证）
            boolean sadmin = subject.hasRole("sadmin");
            System.out.println(sadmin + "拥有sadmin角色");
            boolean permitted = subject.isPermitted("find:*:*");
            System.out.println(permitted + "拥有find:*:*权限");

            //如果验证通过
            if (subject.isAuthenticated()) {
                HashMap<String, String> userInfo = new HashMap<>();
                userInfo.put("uname", user.getUname());

                //获取token
                String token = JWTUtils.getToken(userInfo);
                return token;
            } else {
                return "redirect:/error.html";
            }

        } catch (UnknownAccountException e) {
            e.printStackTrace();
            return "redirect:/error.html";
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            return "redirect:/error.html";
        }
    }

    /**
     * 用于用户注册
     *
     * @return
     */
    @PostMapping("/regi")
    @CrossOrigin
    public String regi(@RequestBody User user) {
        System.out.println(user);
        try {
            User userByUname = userService.findUserByUname(user.getUname());
            if (userByUname != null) {
                System.out.println("注册失败！！！");
                return "redirect:/error.html";
            }
            userService.register(user);
            return "redirect:/login.html";
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("注册失败！！！");
            return "redirect:/error.html";
        }
    }


    @RequestMapping("/loginOut")
    @CrossOrigin
    public String loginOut() {
        SecurityUtils.getSubject().logout();
        System.out.println("退出");
        return "redirect:/Out.html";
    }


    @GetMapping("/tt")
    @CrossOrigin

    public String test() {
        return "dfsdsd";
    }

    @RequestMapping(value = "/tokenLog", method = RequestMethod.POST)
    @CrossOrigin

    public String loginHaveToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        String s = JWTUtils.testSign(token).getClaim("uname").asString();
        return s != null ? "success" + s : "令牌失效！！！";
    }

}
